package com.sofwin.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sofwin.dto.SResourceDto;
import com.sofwin.pojo.SResource;
import com.sofwin.service.SResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("system/resource")
public class ResourceController {
    @Autowired
    private SResourceService resourceService;

    @RequestMapping("data")
    public String data(Model model) throws JsonProcessingException {
        //List<SResourceDto> Trees = resourceService.selectAllResourceToTree();
        //ObjectMapper objectMapper = new ObjectMapper();
        //String string = objectMapper.writeValueAsString(Trees);
        //model.addAttribute("string",string);
        List<SResourceDto> Trees = resourceService.selectAllResourceToTree();
        model.addAttribute("resources", Trees);
        return "resource/data";
    }

    @RequestMapping("createTree")
    @ResponseBody
    public List createTree(Integer flag,Integer roleId) {
        // 用户个人的资源管理
        if (flag != null && flag ==1){
            //List<SResourceDto> SelectTree = resourceService.selectAllResourceToTreeByRoleId(roleId);
            List<SResource> SelectTree = resourceService.selectAllResourceToTreeByRoleId(roleId);
            return SelectTree;
        }
        // 树的生成
        return resourceService.selectAllResourceToTree2();
    }

    @RequestMapping("save")
    @ResponseBody
    public Map save(SResource sResource) {
        Map map = new HashMap();
        boolean status = resourceService.save(sResource);
        map.put("status", status);
        return map;
    }
    @PostMapping("getResource")
    @ResponseBody
    public SResource getResource(Integer id){
        return resourceService.selectByIdForTree(id);
    }

    @PostMapping("deleteNode")
    @ResponseBody
    public Map deleteNode(Integer id){
        Map map = new HashMap();
        boolean status = resourceService.deleteNode(id);
        map.put("status",status);
        return map;
    }
}
